package com.slz.crm.server.handler;


import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result<String> serviceException(ServiceException e) {

        log.error(e.getMessage(), e);

        return Result.error("服务异常，请稍后重试");
    }

    @ExceptionHandler(BaseException.class)
    public Result<String> exceptionHandler(BaseException ex) {
//        log.error("业务异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<String> handleTypeMismatch(MethodArgumentTypeMismatchException e) {
        // 获取参数名和期望类型
        String paramName = e.getName();
        String expectedType = Objects.requireNonNull(e.getRequiredType()).getSimpleName();
        String value = e.getValue() != null ? e.getValue().toString() : "null";
        String format = String.format("参数 [%s] 格式错误，期望类型：%s，实际值：%s", paramName, expectedType, value);

        return Result.error(format);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> handleHttpMessageNotReadable(HttpMessageNotReadableException e) {
        // 提取错误信息（如 "Cannot deserialize value of type `java.time.LocalDate` from String..."）
        String message = e.getMessage();
        // 简化提示（可根据实际需求优化）
        if (message.contains("LocalDate")) {
            message = "日期格式错误，期望格式：yyyy-MM-dd HH:mm:ss";
        }
        return Result.error(message);
    }


}
